const fs = require('fs');
const path = require('path');
const logger = require('log4js').getLogger();
const files = require('../model/Files');
const config = require('../../config/config');

let upload = async (user_id, file) => {

    let target = getFileInfo(file);

    logger.debug('--file upload target --', target);

    mkdirsSync(target.targetPaths);

    let stream = fs.createWriteStream(target.resultPath);//创建一个可写流
    fs.createReadStream(file.path).pipe(stream);
    fs.unlinkSync(file.path);


    let f_id = await files.addFile([user_id, target.relativePath + '/' + target.targetName, file.name, file.size, file.type, Date.now()]);

    let sync_file = await files.query(f_id);

    return sync_file;
}


function getFileInfo(file) {
    let extensionName = path.extname(file.name);
    let theData = new Date();
    let timeName = (Date.parse(new Date()) / 1000) + '' + (Math.round(Math.random() * 9999));
    let targetPaths = theData.getFullYear() + '-' + (theData.getMonth() + 1) + '-' + theData.getDate();
    let relativePath = '/' + targetPaths;
    targetPaths = config.FILE_ROOT + relativePath;
    let targetName = timeName + extensionName;
    let resultPath = targetPaths + '/' + targetName;
    return {targetName: targetName, targetPaths: targetPaths, resultPath: resultPath, relativePath: relativePath}
}


function mkdirsSync(dirname) {
    //console.log(dirname);
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

let queryFile = async (file_id) => {
    let db_file =  await files.query(file_id);
    if(db_file && db_file.length == 1){
        return db_file[0];
    }
    return null;
}

module.exports = {
    upload,
    queryFile
}